<?php

namespace frontend\modules\business\controllers;

use common\components\Upload;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessGrowup;
use common\models\business\BusinessPig;
use common\models\business\BusinessUser;
use common\models\business\BusinessUserScorerecord;
use common\models\shop\ShopOrder;
use common\models\shop\ShopRaisingOrder;
use common\models\shop\ShopUserAddress;
use common\models\sys\SysSetting;
use EasyWeChat\Support\Url;
use frontend\controllers\BaseMobileController;
use yii\captcha\CaptchaValidator;
use yii\db\Query;
use Yunpian\Sdk\YunpianClient;


/**
 * Class PersonController
 * @package frontend\modules\business\controllers
 * 用户相关控制器
 */
class UserController extends BaseMobileController
{



    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                //'backColor'=>0x000000,//背景颜色
                'maxLength' => 4, //最大显示个数
                'minLength' => 4,//最少显示个数
                //'padding' => 5,//间距
                'height'=>30,//高度
                'width' => 50,  //宽度
                // 'foreColor'=>0xffffff,     //字体颜色
                //'offset'=>4,        //设置字符偏移量 有效果
                //'controller'=>'login',        //拥有这个动作的controller
            ],
        ];
    }

//
//        {name:"个人资料",icon:"user2",link:"userinfo.html",color:"mx_green"},
//        {name:"地址管理",icon:"location",link:"address_list.html",color:"danger"},
//        {name:"我的仔猪",icon:"pig",link:"mypigs.html",color:"info"},
//        {name:"农家乐订单",icon:"list2",link:"order_list.html",color:"mx_green"},
//        {name:"猪肉订单",icon:"list1",link:"order_list.html",color:"danger"},
//        {name:"农家体验",icon:"heart",link:"farm_experience.html",color:"info"}

    /**
     * @var array
     * 个人中心菜单
     */
    public static $menus = [
        ['name' => '个人资料','icon'=>"user2",'color'=>"danger",'link' => 'user-info'],
        ['name' => '地址管理','icon'=>"location",'color'=>"info",'link' => '/business/user/address/index'],
        ['name' => '我的认养','icon'=>"pig",'color'=>"mx_green",'link' => '/business/user/my-pigs'],
//        ['name' => '农家乐订单','icon'=>"list2",'color'=>"mx_green",'link' => '/business/user/farmer-house-order/index'],
        ['name' => '商城订单','icon'=>"list1",'color'=>"danger",'link' => '/business/user/pork-order/index'],
        ['name' => '农家体验','icon'=>"heart",'color'=>"info",'link' => '/business/user/farmer-experience/index'],
        ['name' => '认养订单','icon'=>"heart",'color'=>"info",'link' => '/business/user/pig-order/index'],
    ];






    /**
     * @return string
     * 个人中心
     */
    public function actionIndex()
    {
        $user = BusinessUser::find()->select('id,score,nickname,avatar')->where('id=:id',[':id'=>$this->user['userid']])->asArray()->one();

        //取出客服电话
        $custome_tel = SysSetting::getValue('custom_tel');
        return $this->render('@template/mobile/usercenter.html',[
            'menus' => \GuzzleHttp\json_encode(self::$menus),
            'user' => $user,
            'score' => $user['score'],
            'custom_tel' => $custome_tel
        ]);

    }




    /**
     * @return string
     * 个人资料
     */
    public function actionUserInfo()
    {
//        if(!empty($this->user['userid'])){
//            $user = BusinessUser::find()->select('*,phone as tel,nickname as name')->where('id=:id',[':id'=> $this->user['userid']])->asArray()->one();
//        }else{
//            $user = BusinessUser::find()->select('*,phone as tel,nickname as name')->where('id=:id',[':id'=> 1])->asArray()->one();
//        }
        $user = BusinessUser::find()->select('*,phone as tel,nickname as name')->where('id=:id',[':id'=> $this->user['userid']])->asArray()->one();

        return $this->render('@template/mobile/userinfo.html',[
            'userinfo' => \GuzzleHttp\json_encode($user),
            'isperson' => 0,
        ]);
    }


    /**
     * @return array
     * 修改个人资料
     */
    public function actionPostUserinfo()
    {
        $postdata = \Yii::$app->request->post();


        $tel = \Yii::$app->db->createCommand('select phone from '.BusinessUser::tableName().' where id=:id')
            ->bindValues([':id'=>$this->user['userid']])
            ->queryScalar();

        //更改手机验证手机号码
        if($postdata['tel'] != $tel){
            if(\Yii::$app->session->get('smscode') != $postdata['code']){
                return $this->jsonMsg('短信验证码错误',1);
            }
        }

        $data = [
            'nickname' => $postdata['name'],
            'phone' => $postdata['tel'],
            'descripation' => $postdata['descripation'],
            'gender' => $postdata['gender'],
        ];
        $res = \Yii::$app->db->createCommand()->update(BusinessUser::tableName(),$data,'id=:id',[':id'=>$this->user['userid']])->execute();
        $url = \yii\helpers\Url::to(['/business/user/index']);
        return ($res||$res==0)?$this->jsonMsg('更新成功',0,['url' => $url]):$this->jsonMsg('网络问题',1);
    }


    /**
     * @return string
     * 积分记录
     */
    public function actionScoreRecord()
    {
        $record = (new Query())->select('FROM_UNIXTIME(createtime) as time,remark as title,score as credit')->from(BusinessUserScorerecord::tableName())->where('userid=:uid',[':uid'=>$this->user['userid']])->all();

        return $this->render('@template/mobile/scorerecord.html',[
            'record' => \GuzzleHttp\json_encode($record)
        ]);
    }


    public function actionMyPigs()
    {
        $status = \Yii::$app->request->get('status');
        /**
         * 取出仔猪信息
         */
        $query = (new Query())->select('p.id as pigid,o.pigvariety,p.photo,p.status,f.address,f.addressdetail,p.status')
            ->from(ShopRaisingOrder::tableName().' as o')
            ->leftJoin(BusinessPig::tableName().' as p','p.id=o.pigid')
            ->leftJoin(BusinessFarmers::tableName().' as f','p.livery=f.id');

        if($status){
            $pig = $query->where('o.userid=:uid and p.status=:status and o.status>=:ostatus',[':uid'=>$this->user['userid'],':status'=>$status,':ostatus'=>ShopOrder::STATUS_PAY])
                ->all();
        }else{
            $pig = $query->where('o.userid=:uid and o.status=:ostatus',[':uid'=>$this->user['userid'],':ostatus'=>ShopOrder::STATUS_PAY])
                ->all();
        }

        $pigs = [];
        foreach ($pig as $key => $row){
            $pigs[$key]['type'] = $row['pigvariety'];
            $pigs[$key]['status'] = BusinessPig::$statues[$row['status']];
            $pigs[$key]['address'] = $row['addressdetail'];
            $pigs[$key]['img'] = Upload::checkGetUrl($row['photo'],false,'photo');
            if($row['status'] == BusinessPig::STATUS_WAITOUT){
                $oid = BusinessGrowup::find()->select('id')->where('pigid=:id',[':id'=>$row['pigid']])->asArray()->scalar();
                $pigs[$key]['url'] =\yii\helpers\Url::to(['/business/user/sel-killtype','growid'=>$oid]);
                $pigs[$key]['btn'] = '确认宰杀';
            }else{
                $pigs[$key]['url'] =\yii\helpers\Url::to(['/business/user/pig-order/pigs-detail','id'=>$row['pigid']]);
                $pigs[$key]['btn'] = '查看详情';
            }
        }
        unset($pig);

        return $this->render('@template/mobile/mypigs.html',[
            'pigs' => \GuzzleHttp\json_encode($pigs),
            'status' => $status
        ]);

    }


    /**
     * @param $growid
     * @return string
     * 确认宰杀方式
     */
    public function actionSelKilltype($growid)
    {
        $kill = SysSetting::getValue('killtype');
        foreach ($kill as $key => $row){
            $tdata = explode('@',$row);
            $data['title'] = $tdata[0];
            $data['price'] = $tdata[1];
            $data['desc'] = $tdata[2];
            $info[] =  $data;
        }

//        $info = [
//            ['title' => '土杀方式','desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。','price'=>200],
//            ['title' => '屠宰场宰杀','desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。','price'=>300],
//        ];

        $growup = (new Query())->select('id,reason,descripation,createtime,pigid')
            ->from(BusinessGrowup::tableName())
            ->where('id=:id',[':id'=>$growid])
            ->one();

        return $this->render('@template/mobile/selkilltype.html',[
            'growup' => $growup,
            'info' => \GuzzleHttp\json_encode($info)
        ]);
    }


    /**
     * @return array
     * 提交宰杀方式
     */
    public function actionPostKilltype()
    {
        $postdata = \Yii::$app->request->post();
        $data = [
            'killtype' => $postdata['killtype'],
            'killprice' => $postdata['killprice'],
            'paytype' => 1,     //默认微信支付
            'ordersn' => date('ymdHi').$this->user['userid'].rand(10,99),
            'userid' => $this->user['userid'],
        ];
        $res = \Yii::$app->db->createCommand()->update(BusinessGrowup::tableName(),$data,'id=:id',[':id'=>$postdata['id']])->execute();

        return $res?$this->jsonMsg('确认成功',0):$this->jsonMsg('确认失败',1);

    }


    /**
     * 获取短信验证码
     */
    public function actionSmsCode()
    {
        $code = rand(10000,99999);
        $postdata = \Yii::$app->request->post();
        $caprcha = new CaptchaValidator();
        if(!$this->createAction('captcha')->validate($postdata['pcode'], false)){
            return \GuzzleHttp\json_encode(['msg'=>'图形验证码有误','status'=>1]);
        }


        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create('007cd011067a796fb688cef1473dbf7e');
        \Yii::$app->session->set('smscode',$code);
        if(empty($this->user['nickname'])){
            $this->user['nickname'] = '用户';
        }
        $param = [YunpianClient::MOBILE => $postdata['tel'],YunpianClient::TEXT => '【牧心农业】亲爱的'.$this->user['nickname'].'，您的验证码是'.$code.'。有效期为20分钟，请尽快验证。'];
        $r = $clnt->sms()->single_send($param);
//        if($r->code != 0){
//            return json_encode(['msg'=>$r->msg,'status'=>1]);
//        }
//        return json_encode(['msg'=>$r->msg,'status'=>0]);
        return json_encode(['msg'=>'短信发送成功','status'=>0]);

    }


}